package cn.jpush.api.examples;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.yls.except.util.StringIsempty;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

public class PushExample {
	private static final String STATAPPKEY = "9307cc0356e5b992f352e0a3";
	private static final String STATMASTERSECRET = "26014dcbbdb28bf34488cdde";
	private static final String CLOUDAPPKEY = "ee0a5e7c9619fe4c069e4180";
	private static final String CLOUDMASTERSECRET = "71668770e6c1225f4de975dc";
	public static final String TITLE = "！";
	public static final String ALERT = "";
	public static final String MSG_CONTENT = "";
	// "020c1e3a0b6"
	public static final String TAG = "tag_api";

	/*
	 * public static void main(String[] args) { SendPush(); }
	 */

	public static void SendPushToMany(List<String> registrationIds,
			String taskNum, String messagetype) {
		// HttpProxy proxy = new HttpProxy("localhost", 3128);
		// Can use this https proxy: https://github.com/Exa-Networks/exaproxy
		// For push, all you need do is to build PushPayload object.
		PushPayload payload = buildPushObject_android_and_ios(registrationIds,
				taskNum, messagetype);
		System.out.println("传入的registrationId" + registrationIds);
		PushResult result = getResult(payload);
	}

	/**
	 * 向用户发送一条通知，通知该用户有任务被就收了
	 * @param registrationId
	 * @param taskNum
	 * @param uid
     */
	public static void SendPushToOne1(String registrationId, String taskNum,
			String uid) {
		PushPayload payload = buildPushObject_android_and_ios1(registrationId,
				taskNum, uid);
		System.out.println("传入的registrationId" + registrationId);
		PushResult result = getResult(payload);
	}

	/**
	 * 向用户发送一条透传消息 通知用户有多少人接受到了他发布任务的消息通知
	 * @param registrationId
	 * @param pushPersonNum
	 */
	// 向用户发送一条透传消息 通知用户有多少人接受到了他发布任务的消息通知
	public static void SendPushToOne(String registrationId,
			String pushPersonNum, String indentnum) {
		PushPayload payload = buildPushObject_android_and_ios2(registrationId,
				pushPersonNum, indentnum);
		System.out.println("传入的registrationId" + registrationId);
		PushResult result = getResult(payload);
	}

	/**
	 * 
	 * @param registrationId
	 *            设备标示
	 * @param text
	 *            消息类型说明
	 * @param noReadNum
	 *            消息未读数量
	 * @param type
	 *            推送消息类型
	 * @param uid
	 *            被推送消息的用户id
	 */
	public static void SendPushToOneMessage(String registrationId, String text,
			String noReadNum, String type, String uid) {
		PushPayload payload = buildPushObject_android_and_ios9(registrationId,
				text, noReadNum, type, uid);
		System.out.println("传入的registrationId：" + registrationId + text
				+ "的推送消息");
		PushResult result = getResult(payload);
	}

	// 消息透传（1、任务被接受了、2、申请加为好友了、3、动态被回复了、4、动态被点赞了、5、动态被转发、6、验证审核消息 7、好友发布动态
	// 8、系统消息、）
	public static PushPayload buildPushObject_android_and_ios9(
			String registrationId, String text, String noReadNum, String type,
			String uid) {
		System.out.println("透传消息");
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(registrationId))
				.setMessage(
						Message.newBuilder().setMsgContent("title")
								.setTitle("消息").addExtra("text", text)
								.addExtra("noReadNum", noReadNum)
								.addExtra("uid", uid)
								.addExtra("messageType", type).build()).build();
	}

	// 想所有用户发送一条透传，以便前台在任务被抢先接受的情况下修改前台任务显示的状态
	public static void SendPushToall(String taskNum, String taskState) {
		JSONObject msgContent = new JSONObject();
		try {
			msgContent.put("taskNum", taskNum);
			msgContent.put("taskState", taskState);
			msgContent.put("messageType", 300);
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		PushPayload payload = buildPushObject_all_all_alert(msgContent
				.toString());
		PushResult result = getResult(payload);
	}

	// 向所有用户发送一条消息
	public static PushPayload buildPushObject_all_all_alert(String msgContent) {
		return PushPayload.messageAll(msgContent);
	}

	public static PushPayload buildPushObject_all_alias_alert() {
		return PushPayload.newBuilder().setPlatform(Platform.all())
				.setAudience(Audience.alias("alias1"))
				.setNotification(Notification.alert(ALERT)).build();
	}

	public static PushPayload buildPushObject_android_tag_alertWithTitle() {
		return PushPayload.newBuilder().setPlatform(Platform.android())
				.setAudience(Audience.tag("tag1"))
				.setNotification(Notification.android(ALERT, TITLE, null))
				.build();
	}

	// 平台是Android与ios 推送目标是registrationIds的集合 推送的是通知
	public static PushPayload buildPushObject_android_and_ios(
			List<String> registrationIds, String taskNum, String messagetype) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(registrationIds))
				.setNotification(
						Notification
								.newBuilder()
								.setAlert("")
								.addPlatformNotification(
										AndroidNotification
												.newBuilder()
												.setTitle("通知！")
												.addExtra("text", "")
												.setBuilderId(1)
												.addExtra("taskNum", taskNum)
												.addExtra("messageType",
														messagetype).build())
								.addPlatformNotification(
										IosNotification.newBuilder()
												.incrBadge(1).build()).build())
				.build();
	}

	// 任务被接受了 ，推送一条透传给发布任务的用户
	public static PushPayload buildPushObject_android_and_ios1(
			String registrationId, String taskNum, String uid) {
		System.out.println("透传消息");
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(registrationId))
				.setMessage(
						Message.newBuilder().setMsgContent("")
								.setTitle("透传").addExtra("taskNum", taskNum)
								.addExtra("receiveTaskUid", uid)
								.addExtra("messageType", "200").build())
				.build();
	}

	// 平台是Android与ios 推送目标是registrationId 的设备 透传推送
	public static PushPayload buildPushObject_android_and_ios2(
			String registrationId, String pushPersonNum, String indentNum) {
		System.out.println("透传消息");
		System.out.println("id:" + registrationId + "    pushPersonNum:"
				+ pushPersonNum + "    indentNum:" + indentNum);
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(registrationId))
				.setMessage(
						Message.newBuilder().setMsgContent("透传")
								.setTitle("透传")
								.addExtra("indentNumber", indentNum)
								.addExtra("pushPerson", pushPersonNum)
								.addExtra("messageType", "100").build())
				.build();
	}

	public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.ios())
				.setAudience(Audience.tag_and("tag1", "tag_all"))
				.setNotification(
						Notification
								.newBuilder()
								.addPlatformNotification(
										IosNotification.newBuilder()
												.setAlert(ALERT).setBadge(5)
												.setSound("happy")
												.addExtra("from", "JPush")
												.build()).build())
				.setMessage(Message.content(MSG_CONTENT))
				.setOptions(
						Options.newBuilder().setApnsProduction(true).build())
				.build();
	}

	public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(
						Audience.newBuilder()
								.addAudienceTarget(
										AudienceTarget.tag("tag1", "tag2"))
								.addAudienceTarget(
										AudienceTarget
												.alias("alias1", "alias2"))
								.build())
				.setMessage(
						Message.newBuilder().setMsgContent(MSG_CONTENT)
								.addExtra("from", "JPush").build()).build();
	}
	
	
	/**
	 * 推送
	 * 
	 * @param registrationId 极光标识
	 * @param text 内容
	 * @param noReadNum 未读消息总条数
	 * @param type 类型
	 * @param typeid 类型id
	 * @param state
	 *        
	 */
	public static void SendJpushToOneMessage(String registrationId,String text, String noReadNum, String type, String state,String typeid, String uid, String orderid, String usertype) {
		PushPayload pushPayload = buildPushObject_android_and_ios10(registrationId,text, noReadNum, type, state, typeid, uid, orderid);
		Logger logger = Logger.getLogger(PushExample.class);
		logger.info("极光推送信息：title：" + text + ",usertype:" + usertype + ",registrationId:" + registrationId);
		System.out.println("传入的registrationId：" + registrationId + text+ "的推送消息");
		if("0".equals(usertype))
			getStatResult(pushPayload);
		else
			getCloudResult(pushPayload);
	}

	public static PushResult getResult (PushPayload pushPayload) {
		JPushClient jpushClient = new JPushClient(STATMASTERSECRET, STATAPPKEY, 3);
		try {
			return jpushClient.sendPush(pushPayload);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static PushResult getStatResult (PushPayload pushPayload) {
		JPushClient jpushClient = new JPushClient(STATMASTERSECRET, STATAPPKEY, 3);
		try {
			return jpushClient.sendPush(pushPayload);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static PushResult getCloudResult (PushPayload pushPayload) {
		JPushClient jpushClient = new JPushClient(CLOUDMASTERSECRET, CLOUDAPPKEY, 3);
		try {
			return jpushClient.sendPush(pushPayload);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 推送
	 * 
	 * @param registrationId
	 *            极光标识
	 * @param text
	 *            内容
	 * @param noReadNum
	 *            未读消息总条数
	 * @param type
	 *            类型
	 * @param typeid
	 *            类型id
	 * @param uid 
	 * @return
	 */
	// 平台是Android与ios 推送目标是registrationId 的设备 透传推送
	public static PushPayload buildPushObject_android_and_ios10(
			String registrationId, String text, String noReadNum, String type,
			String state, String typeid, String uid, String orderid) {
		return PushPayload
				.newBuilder()
				.setPlatform(Platform.android_ios())
				.setAudience(Audience.registrationId(registrationId))
				.setMessage(
						Message
						.newBuilder()
						.setMsgContent("title")
						.setTitle("消息")
						.addExtra("text", text)
						.addExtra("noReadNum", noReadNum)
						.addExtra("messageType", type)
						.addExtra("state", state)
						.addExtra("uid", uid)
						.addExtra("orderid", orderid)
						.addExtra("typeid", typeid)
						.build()).build();
	}
	
	
	public static void SendJpushToOneMessage(Map<String, Object> map) {
		if(map == null)
			return;
		if(StringIsempty.isallempty(map.get("phone") + ""))
			map.put("phone", "");
		String usertype = map.get("usertype") + "";
		Logger logger = Logger.getLogger(PushExample.class);
		logger.info("极光推送信息：title：" + map.get("text") + ",usertype:" + usertype + ",registrationId:" + map.get("jpushtag"));
		JPushClient jpushClient;
		if("0".equals(usertype))
			jpushClient = new JPushClient(STATMASTERSECRET, STATAPPKEY, 3);
		else
			jpushClient = new JPushClient(CLOUDMASTERSECRET, CLOUDAPPKEY, 3);
		try {
			PushPayload pushPayload = PushPayload
					.newBuilder()
					.setPlatform(Platform.android_ios())
					.setAudience(Audience.registrationId(map.get("jpushtag") + ""))
					.setMessage(
							Message.newBuilder().setMsgContent("title")
							.setTitle("消息")
							.addExtra("text", map.get("text") + "")
							.addExtra("noReadNum", map.get("noreadnum") + "")
							.addExtra("messageType", map.get("type") + "")
							.addExtra("state", map.get("state") + "")
							.addExtra("typeid", map.get("typeid") + "")
							.addExtra("money", map.get("money") + "")
							.addExtra("uid", map.get("uid") + "")
							.addExtra("phone", map.get("phone") + "")
							.build()
						).build();
			PushResult result = jpushClient.sendPush(pushPayload);
			System.out.println(result + "这里是推送返回的数据");
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 封装极光推送信息
	 * @param text  内容
	 * @param noreadnum 未读条数
	 * @param type 推送类型（0：下线提示）
	 * @param state
	 * @param typeid  类型id
	 * @param money 金额
	 * @param uid 用户id
     * @param phone 电话号码
     * @return
     */
	public static void getPushmap(String text, int noreadnum, int type, int state, String typeid, String money, String uid, String phone, String jpushtag, String usertype){
		Map<String, Object> pushmap = new HashMap<String, Object>();
		pushmap.put("text", text);
		pushmap.put("jpushtag", jpushtag);
		pushmap.put("noreadnum", noreadnum);
		pushmap.put("type", type);
		pushmap.put("state", state);
		pushmap.put("typeid", typeid);
		pushmap.put("money", money);
		pushmap.put("uid", uid);
		pushmap.put("phone", phone);
		pushmap.put("usertype", usertype);
		SendJpushToOneMessage(pushmap);
	}
}
